package org.gwu.seuss.server.command;

import org.gwu.seuss.communication.request.ClientRequest;
import org.gwu.seuss.communication.request.ServerResponse;
import org.gwu.seuss.domain.File;
import org.springframework.util.Assert;

public class DownloadCommand extends UserCommandBase implements Command {

	public DownloadCommand(ClientRequest req) {
		super(req);
	}

	@Override
	public ServerResponse execute() throws Exception {
		String username = req.getUsername();

		Assert.hasText(username, "Username is not provided.");

		userService.authorizeUser(req);
		log.info("User " + username + "requested to download "
				+ req.getFileId());

		byte[] decFile = fileService.downloadFile(req);
		File file = this.fileService.selectFileById(req.getFileId());

		ServerResponse rep = new ServerResponse();
		rep.setSuccess(true);
		rep.setMessage("File downloaded.");
		rep.setFileBytes(decFile);
		rep.setFilename(file.getFilename());

		log.info("Download action successful for file " + file.getFilename());
		return rep;

	}
}